package org.jash.sportnews2109.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.databinding.ObservableArrayMap
import androidx.databinding.ObservableMap
import com.alibaba.android.arouter.facade.annotation.Route
import org.jash.common.logging
import org.jash.common.mvvm.BaseActivity
import org.jash.common.token
import org.jash.sportnews2109.R
import org.jash.sportnews2109.databinding.ActivityPhoneBinding
import org.jash.sportnews2109.vm.PhoneViewModel
@Route(path = "/news/phone")
class PhoneActivity : BaseActivity<ActivityPhoneBinding, PhoneViewModel>() {
    val map by lazy { ObservableArrayMap<String, String>() }
    override fun initView() {
        binding.map = map
        binding.verify.setOnClickListener {
            viewModel.getVerifyCode(map["phone"] ?: "")
        }
        binding.login.setOnClickListener {
            viewModel.login(map)
        }
        binding.phoneNumber.editText?.addTextChangedListener {
            binding.phoneNumber.isErrorEnabled = false
            if (map["phone"]?.length !in listOf(0, 11)) {
                binding.phoneNumber.isErrorEnabled = true
                binding.phoneNumber.error = "手机号不合法"
            }
        }
        binding.verifyCode.editText?.addTextChangedListener {
            binding.verifyCode.isErrorEnabled = false
            if (map["phone"]?.length !in listOf(0, 6)) {
                binding.verifyCode.isErrorEnabled = true
                binding.verifyCode.error = "验证码不合法"
            }
        }
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun initData() {
        viewModel.tokenLiveData.observe(this, this::success)
        viewModel.verifyLiveData.observe(this, this::getVerifyCode)
    }
    fun getVerifyCode(code:String) {
        Toast.makeText(this, "验证码: $code", Toast.LENGTH_SHORT).show()
        map["code"] = code
    }
    fun success(t:String) {
        token = t
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
        logging("token: $token")
        finishAffinity()
    }

}